#include <stdio.h>
#include <esp_system.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nvs.h>
#include <nvs_flash.h>
#include "device/device.h"
#include "led/led.h"
#include "nvs/value.h"
#include "ws2812/ws2812.h"

void run_tasks(){
    run_restart_task(300);
    //run_led_blink_task(500, 3000, 0);
    run_led_fade_task();
    run_ws2812_task();
}

void app_main(void)
{
    // log device info
    log_esp_info();

    printf("portTICK_PERIOD_MS = %ld\n", portTICK_PERIOD_MS);

    // Initialize NVS
    ESP_LOGI("ESP", "initialize NVS\n");
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    // Open
    printf("\n");
    printf("Opening Non-Volatile Storage (NVS) handle... \n");
    nvs_handle_t nvs_handle;
    err = nvs_open("storage", NVS_READWRITE, &nvs_handle);
    if (err != ESP_OK)
    {
        printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
        return;
    }
    else
    {
        printf("NVS Done\n");
    }

    log_nvs_info(nvs_handle);

    // Close NVS
    nvs_close(nvs_handle);

    run_tasks();
}
